import * as d3 from "d3";
import React from "react";
import { useRequest } from "ahooks";
import ClipLoader from "react-spinners/ClipLoader";
import { Skeleton } from "@/components/ui/skeleton";
import { VbpStatsByCadnI } from "@/types/api";
import { getVbpStatsByCadnVbp } from "@/api";
import { dayjs } from "@/App";
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
import PieChartByCadnVbp from "./components/pie_chart_by_cadn_vbp";
import { useSelector } from "react-redux";
import { useToast } from "@/hooks/use-toast";
import { RootStateI } from "@/types";

const VbpStats = (): JSX.Element => {
  const location = useLocation();
  const [searchParams] = useSearchParams();
  const [vbpStatsList, setVbpStatsList] = React.useState<VbpStatsByCadnI[]>([]);
  const [startDate, setStartDate] = React.useState<Date>(); // 查询结果第一条的批次开始时间
  const [endDate, setEndDate] = React.useState<Date>(); // 查询结果第一条的批次结束时间
  const [selectedBatch, setSelectedBatch] = React.useState<string>("%"); // 提交数据时选择的批次，只选一个批次时显示批次时间的消耗情况
  const [totalDays, setTotalDays] = React.useState<number>(0);
  const [elapsedDays, setElapsedDays] = React.useState<number>(0);
  const user = useSelector((state: RootStateI) => state.user);
  const { toast } = useToast();

  const colorScale: any = d3
    .scaleLinear()
    .domain([0, 1])
    .range(["green", "red"] as any);

  // 获取可视化数据，一次取全部
  const { loading: loadingChartData, run: runByCadn } = useRequest(
    (paramsString: string) => getVbpStatsByCadnVbp(paramsString),
    {
      manual: false,
      defaultParams: [location.search.replace(/^\?/, "")],
      onSuccess(resp: any, params: any) {
        console.log(resp);
        setVbpStatsList(resp.data.data);

        if (resp.data.data.length) {
          const startDate = dayjs(resp.data.data[0].startDate);
          if (startDate.isValid()) {
            setStartDate(startDate.toDate());
          }
          const endDate = dayjs(resp.data.data[0].endDate);
          if (endDate.isValid()) {
            setEndDate(endDate.toDate());
          }

          const totalDays = Math.abs(
            Math.round(
              endDate.diff(startDate, "millisecond") / (1000 * 60 * 60 * 24)
            )
          );
          const elapsedDays = Math.abs(
            Math.round(
              dayjs().diff(startDate, "millisecond") / (1000 * 60 * 60 * 24)
            )
          );
          // console.log(totalDays);
          // console.log(elapsedDays);
          setTotalDays(totalDays);
          setElapsedDays(elapsedDays);
        }
      },
      onError(e: any, params: any) {
        toast({
          variant: "destructive",
          title: "获取数据失败",
        });
      },
    }
  );

  React.useEffect(() => {
    const urlStartDate = searchParams.get("startDate");
    const urlEndDate = searchParams.get("endDate");
    const urlBatchEndDate = searchParams.get("batchEndDate");
    const urlCadn = searchParams.get("cadn");
    const urlVbpClass = searchParams.get("vbpClass");

    const urlParams = {
      startDate: dayjs(urlStartDate?.replace(/"/g, "")).isValid()
        ? dayjs(urlStartDate?.replace(/"/g, "")).toDate()
        : null,
      endDate: dayjs(urlEndDate?.replace(/"/g, "")).isValid()
        ? dayjs(urlEndDate?.replace(/"/g, "")).toDate()
        : null,
      batchEndDate: urlBatchEndDate?.replace(/"/g, ""),
    };
    setSelectedBatch(urlBatchEndDate?.replace(/"/g, "") || "%");
    console.log(urlParams);

    // run(searchParams.toString());
  }, [searchParams]);

  return (
    <div className="w-full p-6">
      <div className="py-6 min-h-screen">
        <div id="chartContainer" className="w-full">
          <div className="text-center">
            <h3 className="text-2xl font-bold">{`${searchParams
              .get("cadn")
              ?.replace(/"/g, "")}${searchParams
              .get("vbpClass")
              ?.replace(/"/g, "")}品种使用情况`}</h3>
            <div className="w-full flex justify-center">
              {loadingChartData ? (
                <div className="w-full flex justify-center">
                  <Skeleton className="w-[1024px] h-[768px] flex justify-center items-center">
                    数据加载中
                    <ClipLoader
                      loading={loadingChartData}
                      size={50}
                      aria-label="Loading Spinner"
                      data-testid="loader"
                    />
                  </Skeleton>
                </div>
              ) : vbpStatsList.length > 0 ? (
                <div>
                  <span>
                    {selectedBatch == "%" ? (
                      ""
                    ) : (
                      <span
                        style={{ color: colorScale(elapsedDays / totalDays) }}
                      >
                        当前批次从{dayjs(startDate)!.format("YYYY-MM-DD")} 到
                        {dayjs(endDate)!.format("YYYY-MM-DD")}，已经过了
                        <span className="font-bold">
                          {elapsedDays}/{totalDays}
                        </span>
                      </span>
                    )}{" "}
                  </span>
                  <PieChartByCadnVbp
                    data={vbpStatsList}
                    watermarkText={user.username}
                  />
                </div>
              ) : (
                <Skeleton className="w-[1024px] h-[768px] flex justify-center items-center">
                  没有查询结果
                </Skeleton>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default VbpStats;
